<template>
  <div class="friends-list-container">
    <div class="content-card">
      <h2 class="module-title">好友列表</h2>
      <el-input placeholder="搜索好友..." class="friend-search"></el-input>

      <!-- 好友请求功能已迁移至FriendRequestNotification组件 -->

      <!-- 全局空状态 -->
      <div v-if="onlineFriends.length === 0 && offlineFriends.length === 0 && !loading" class="empty-state global-empty">
        <el-icon><UserFilled /></el-icon>
        <p>还没有好友</p>
        <p class="empty-tip">快去添加一些好友吧！</p>
      </div>

      <!-- 在线好友分组 -->
      <div v-else class="friend-group">
        <div class="group-header" @click="toggleGroup('online')">
          <span>在线好友 ({{onlineFriends.length}})</span>
          <el-icon>
            <ArrowDown v-if="expandedGroups.online" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <div class="friend-list" v-if="expandedGroups.online">
          <!-- 在线好友列表 -->
          <div v-if="onlineFriends.length > 0">
            <div class="friend-item" v-for="friend in onlineFriends" :key="friend.id">
              <img 
                :src="friend.avatar || '/images/default-avatar.png'" 
                :alt="friend.username" 
                class="friend-avatar"
                @error="$event.target.src='/images/default-avatar.png'"
                @click="goToUserProfile(friend.friendId)"
              >
              <div class="friend-info">
                <div class="friend-name">{{ friend.remark || friend.username }}</div>
                <div class="friend-original-name" v-if="friend.remark">{{ friend.username }}</div>
                <div class="friend-status online">在线</div>
              </div>
              <div class="friend-actions">
                <el-button @click="startChat(friend)" type="primary" size="small" class="action-btn">
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
                <el-button @click="editRemark(friend)" type="info" size="small" class="action-btn">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button @click="deleteFriend(friend)" type="danger" size="small" class="action-btn">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          <!-- 空状态 -->
          <div v-else class="empty-state">
            <el-icon><UserFilled /></el-icon>
            <p>暂无在线好友</p>
          </div>
        </div>
      </div>

      <!-- 离线好友分组 -->
      <div class="friend-group">
        <div class="group-header" @click="toggleGroup('offline')">
          <span>离线好友 ({{offlineFriends.length}})</span>
          <el-icon>
            <ArrowDown v-if="expandedGroups.offline" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <div class="friend-list" v-if="expandedGroups.offline">
          <!-- 离线好友列表 -->
          <div v-if="offlineFriends.length > 0">
            <div class="friend-item" v-for="friend in offlineFriends" :key="friend.id">
              <img 
                :src="friend.avatar || '/images/default-avatar.png'" 
                :alt="friend.username" 
                class="friend-avatar"
                @error="$event.target.src='/images/default-avatar.png'"
                @click="goToUserProfile(friend.friendId)"
              >
              <div class="friend-info">
                <div class="friend-name">{{ friend.remark || friend.username }}</div>
                <div class="friend-original-name" v-if="friend.remark">{{ friend.username }}</div>
                <div class="friend-status offline">离线</div>
              </div>
              <div class="friend-actions">
                <el-button @click="startChat(friend)" type="primary" size="small" class="action-btn">
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
                <el-button @click="editRemark(friend)" type="info" size="small" class="action-btn">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button @click="deleteFriend(friend)" type="danger" size="small" class="action-btn">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          <!-- 空状态 -->
          <div v-else class="empty-state">
            <el-icon><UserFilled /></el-icon>
            <p>暂无离线好友</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天窗口 -->
    <ChatWindow
      v-if="showChatWindow"
      :visible="showChatWindow"
      :chat-user="currentChatUser"
      :current-user-id="currentUser.id"
      :current-user-avatar="currentUser.avatar"
      @close="closeChatWindow"
      @minimize="minimizeChatWindow"
    />

    <!-- 消息通知 -->
    <MessageNotification
      v-for="notification in messageNotifications"
      :key="notification.id"
      :sender-name="notification.senderName"
      :message-count="notification.messageCount"
      @click="handleNotificationClick(notification)"
      @close="removeNotification(notification.id)"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowDown, ArrowRight, ChatDotRound, Edit, Delete, UserFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '@/utils/axiosConfig';
import ChatWindow from '@/components/ChatWindow.vue';
import MessageNotification from '@/components/MessageNotification.vue';

const router = useRouter();

// 好友数据
const onlineFriends = ref([]);
const offlineFriends = ref([]);
const loading = ref(false);

// 聊天相关状态
const showChatWindow = ref(false);
const currentChatUser = ref({});
const currentUser = ref({});
const messageNotifications = ref([]);

// 分组展开状态
const expandedGroups = ref({
  online: true,
  offline: false
});

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return null;
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.sub ? parseInt(payload.sub) : null;
  } catch (error) {
    console.error('解析token失败:', error);
    return null;
  }
};

// 获取当前用户完整信息
const getCurrentUser = async () => {
  try {
    const response = await axios.get('/auth/profile');
    if (response.data.success) {
      currentUser.value = response.data.data || {};
    }
  } catch (error) {
    console.error('获取当前用户信息失败:', error);
  }
};

// 获取好友列表
const fetchFriends = async () => {
  try {
    loading.value = true;
    console.log('开始获取好友列表...');
    const response = await axios.get('/friends/list');
    console.log('好友列表API响应:', response.data);
    
    if (response.data.success) {
      const friends = response.data.data || [];
      console.log('获取到的好友数据:', friends);
      
      // 根据在线状态分组好友
      onlineFriends.value = friends.filter(friend => friend.isOnline);
      offlineFriends.value = friends.filter(friend => !friend.isOnline);
      
      console.log('在线好友:', onlineFriends.value);
      console.log('离线好友:', offlineFriends.value);
    } else {
      console.error('获取好友列表失败:', response.data.message);
      ElMessage.error(response.data.message || '获取好友列表失败');
    }
  } catch (error) {
    console.error('获取好友列表失败:', error);
    ElMessage.error('获取好友列表失败');
  } finally {
    loading.value = false;
  }
};

// 跳转到用户个人主页
const goToUserProfile = (friendId) => {
  router.push(`/user/${friendId}`);
};

// 发起聊天
const startChat = (friend) => {
  // 设置聊天用户信息
  currentChatUser.value = {
    id: friend.friendId,
    username: friend.username,
    avatar: friend.avatar
  };
  
  // 清除该用户的消息通知
  const notificationIndex = messageNotifications.value.findIndex(
    n => n.senderName === friend.username
  );
  if (notificationIndex > -1) {
    messageNotifications.value.splice(notificationIndex, 1);
  }
  
  // 打开聊天窗口
  showChatWindow.value = true;
};

// 关闭聊天窗口
const closeChatWindow = () => {
  showChatWindow.value = false;
  currentChatUser.value = {};
};

// 最小化聊天窗口
const minimizeChatWindow = () => {
  showChatWindow.value = false;
};

// 编辑好友备注
const editRemark = async (friend) => {
  try {
    const { value: newRemark } = await ElMessageBox.prompt(
      '请输入新的备注名称',
      '编辑好友备注',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: friend.remark || '',
        inputPlaceholder: '请输入备注'
      }
    );
    
    if (newRemark !== null) {
      const response = await axios.put(`/friends/remark/${friend.friendId}`, {
        remark: newRemark
      });
      
      if (response.data.success) {
        ElMessage.success('备注更新成功');
        // 更新本地数据
        friend.remark = newRemark;
      } else {
        ElMessage.error(response.data.message || '备注更新失败');
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新备注失败:', error);
      ElMessage.error('更新备注失败');
    }
  }
};

// 删除好友
const deleteFriend = async (friend) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除好友 "${friend.username}" 吗？`,
      '删除好友',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await axios.delete(`/friends/${friend.friendId}`);
    
    if (response.data.success) {
      ElMessage.success('删除好友成功');
      // 重新获取好友列表
      fetchFriends();
    } else {
      ElMessage.error(response.data.message || '删除好友失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除好友失败:', error);
      ElMessage.error('删除好友失败');
    }
  }
};

// 注意：好友请求功能已移至FriendRequestNotification组件

// 注意：好友请求处理功能已移至FriendRequestNotification组件

// 切换分组展开/折叠
const toggleGroup = (group) => {
  expandedGroups.value[group] = !expandedGroups.value[group];
};

// 处理消息通知点击
const handleNotificationClick = (notification) => {
  // 找到对应的好友
  const friend = [...onlineFriends.value, ...offlineFriends.value].find(
    f => f.username === notification.senderName
  );
  
  if (friend) {
    startChat(friend);
  }
  
  // 移除通知
  removeNotification(notification.id);
};

// 移除消息通知
const removeNotification = (notificationId) => {
  const index = messageNotifications.value.findIndex(n => n.id === notificationId);
  if (index > -1) {
    messageNotifications.value.splice(index, 1);
  }
};

// 添加消息通知
const addMessageNotification = (senderName, messageCount = 1) => {
  // 检查是否已存在该发送者的通知
  const existingNotification = messageNotifications.value.find(
    n => n.senderName === senderName
  );
  
  if (existingNotification) {
    // 更新消息数量
    existingNotification.messageCount += messageCount;
  } else {
    // 创建新通知
    const notification = {
      id: Date.now() + Math.random(),
      senderName,
      messageCount
    };
    messageNotifications.value.push(notification);
  }
};

// 检查未读消息
const checkUnreadMessages = async () => {
  try {
    const response = await axios.get('/messages/unread/details');
    if (response.data.success) {
      const unreadDetails = response.data.data || [];
      
      // 清空现有通知
      messageNotifications.value = [];
      
      // 添加新的通知
      unreadDetails.forEach(detail => {
        addMessageNotification(detail.sender_name, detail.message_count);
      });
    }
  } catch (error) {
    console.error('检查未读消息失败:', error);
  }
};

// 页面加载时获取数据
onMounted(() => {
  const userId = getCurrentUserId();
  if (userId) {
    fetchFriends();
    getCurrentUser();
    checkUnreadMessages();
    
    // 定时检查未读消息（每30秒检查一次）
    const unreadCheckInterval = setInterval(() => {
      checkUnreadMessages();
    }, 30000);
    
    // 组件卸载时清除定时器
    onUnmounted(() => {
      clearInterval(unreadCheckInterval);
    });
  }
  
  // 监听好友请求接受事件
  window.addEventListener('friendRequestAccepted', () => {
    fetchFriends();
  });
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('friendRequestAccepted', () => {
    fetchFriends();
  });
});
</script>

<style scoped>
.friends-list-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.content-card {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  padding: 20px;
  margin-bottom: 20px;
  transition: box-shadow 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.module-title {
  margin-top: 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
  color: #303133;
}

.friend-search {
  margin-bottom: 20px;
}

.friend-group {
  margin-bottom: 15px;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.group-header:hover {
  background-color: #ebeef5;
}

.friend-list {
  padding: 10px;
  background-color: #fafbfc;
  border-radius: 4px;
  margin-top: 8px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
  border-radius: 6px;
  margin-bottom: 4px;
}

.friend-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.friend-item:hover {
  background-color: #f0f2f5;
}

.friend-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
  cursor: pointer;
}

.friend-avatar:hover {
  border-color: #409eff;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.friend-info {
  flex: 1;
  min-width: 0;
}

.friend-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.friend-original-name {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
  font-style: italic;
}

.friend-remark {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.friend-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
  font-weight: 500;
}

.friend-status.online {
  color: #67c23a;
  background-color: #f0f9ff;
  border: 1px solid #b3e19d;
}

.friend-status.offline {
  color: #909399;
  background-color: #f5f7fa;
  border: 1px solid #d3d4d6;
}

.friend-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.friend-item:hover .friend-actions {
  opacity: 1;
}

.action-btn {
  padding: 6px 10px;
  min-width: auto;
  border-radius: 4px;
  transition: all 0.2s;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #909399;
  text-align: center;
}

.empty-state .el-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.empty-state p {
  font-size: 14px;
  margin: 0;
}

.global-empty {
  padding: 80px 20px;
}

.global-empty .el-icon {
  font-size: 64px;
  color: #d1d5db;
  margin-bottom: 20px;
}

.global-empty p {
  font-size: 16px;
  margin-bottom: 8px;
}

.empty-tip {
  font-size: 14px !important;
  color: #c0c4cc !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .friend-item {
    padding: 10px;
  }
  
  .friend-avatar {
    width: 40px;
    height: 40px;
  }
  
  .action-btn {
    padding: 4px 6px;
  }
}

/* 好友请求相关样式已移至FriendRequestNotification组件 */
</style>